#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    db = QSqlDatabase::addDatabase("QMYSQL");
    //db->addDatabase("QMYSQL");
    db.setDatabaseName("employees");
    db.setPort(3306);
    db.setHostName("localhost");
    db.setUserName("root");
    db.setPassword("123456");
    if(db.open()){
        qDebug()<<"mysql connect ok";
    }else {
        qDebug()<<db.lastError().text();
        qDebug()<<"mysql connect failed";
    }

    openTable();
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::openTable()
{
    tableModel = new QSqlTableModel(this, db);
    tableSelection = new QItemSelectionModel(tableModel);
    tableModel->setTable("employees");
    tableModel->setEditStrategy(QSqlTableModel::OnFieldChange);


    if (!tableModel->select()) {
        qDebug()<<"打开数据表错误:"<<tableModel->lastError();
        return;
    }


    connect(tableSelection, SIGNAL(currentChanged(QModelIndex,QModelIndex)), this, SLOT(on_currentChange(QModelIndex,QModelIndex)));
    connect(tableSelection, SIGNAL(currentRowChanged(QModelIndex,QModelIndex)), this, SLOT(on_currentRowChange(QModelIndex,QModelIndex)));

    tableModel->setHeaderData(tableModel->fieldIndex("emp_no"), Qt::Horizontal, "工号");
    ui->tableView->setModel(tableModel);
    ui->tableView->setSelectionModel(tableSelection);



}

void MainWindow::on_currentChange(QModelIndex cur, QModelIndex pre)
{
    Q_UNUSED(cur);
}

void MainWindow::on_currentRowChange(QModelIndex cur, QModelIndex pre)
{
    qDebug()<<cur.row();
}

